package cn.lichenes.log;

import cn.lichenes.entity.Record;
import cn.lichenes.entity.User;
import cn.lichenes.service.RecordService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class LogAspect {

    Record record = new Record();

    @Autowired
    private RecordService recordService;

    @Pointcut("@annotation(cn.lichenes.log.SystemLog)")
    private void recordPoincut(){

    }

    @Before("recordPoincut()")
    public void before(JoinPoint joinPoint){
        Date beginTime = new Date();
        record.setrTime(beginTime);
    }

    @AfterReturning("recordPoincut()")
    public void afterReturning(JoinPoint joinPoint){
        saveLog(joinPoint,"成功");
    }

    @AfterThrowing(pointcut = "recordPoincut()",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint,Exception e){
        saveLog(joinPoint,"失败");
    }

    private void saveLog(JoinPoint joinPoint,String operation){
        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        //获取操作
        SystemLog systemLog = method.getAnnotation(SystemLog.class);
        String status = null;
        if (systemLog != null){
            String value = systemLog.value()+"--"+operation;
            status = systemLog.status();
            record.setrDescription(value);
        }
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        //获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(status);
        if (user != null){
            record.setUser(user);
        }
        recordService.insert(record);
    }
}
